<template>
  <div class="tree-select-item">
    <div class="warp">
      <div>
        <div class="top">
          <div class="left">
            <span :style="{ marginRight: '8px', color: '#529EE9' }">{{ label }}</span>
            <je-switch
              v-model:value="controlQuery"
              mode="checkbox"
              label="可见"
              :disabled="disable"
            />
            <je-switch
              v-model:value="controlEdit"
              mode="checkbox"
              label="可修改"
              :disabled="disable"
            />
            <je-switch
              v-model:value="controlDelete"
              mode="checkbox"
              label="可删除"
              :disabled="disable"
            />
          </div>
          <div :style="{ minWidth: '270PX', textAlign: 'right', color: '#a9aba9' }">{{ info }}</div>
        </div>
        <je-form :model="formState" autocomplete="off">
          <je-form-item v-if="_index === 'userControl'" name="texts">
            <je-input-user
              v-model:value="formState.texts"
              textarea
              class="my-textarea"
              style="height: 100%"
              :select-options="{ title: '人员控制' }"
              :disabled="disable"
              config-info=",ids~texts,USER_ID~text,M"
            />
          </je-form-item>
          <je-form-item v-if="_index === 'roleControl'" name="texts">
            <je-input-select
              v-model:value="formState.texts"
              textarea
              :select-options="selectOptions"
              :disabled="disable"
              class="my-textarea"
              style="height: 100%"
              :order="[{ code: 'SY_ORDERINDEX', type: 'ASC' }]"
              config-info="JE_RBAC_ROLETREE,texts~ids,text~id,M"
              @select="handleSelect"
            >
              <template #nodeIcon="{ row }">
                <i
                  v-if="row.bean.ROLE_TYPE_CODE === 'folder' && row.children.length === 0"
                  class="is--folder fas fa-folder"
                ></i>
              </template>
            </je-input-select>
          </je-form-item>
          <je-form-item v-if="_index === 'deptControl'" name="texts">
            <je-input-select
              v-model:value="formState.texts"
              textarea
              :select-options="{ title: '部门控制' }"
              :disabled="disable"
              class="my-textarea"
              style="height: 100%"
              config-info="JE_RBAC_DEPTTREE,ids~texts,id~text,M"
            />
          </je-form-item>
          <je-form-item v-if="_index === 'orgControl'" name="texts">
            <je-input-select
              v-model:value="formState.texts"
              textarea
              :select-options="{ title: '机构控制' }"
              :disabled="disable"
              class="my-textarea"
              style="height: 100%"
              config-info="JE_RBAC_ORGTREE,ids~texts,id~text,M"
            />
          </je-form-item>
        </je-form>
      </div>
    </div>
  </div>
</template>

<script>
  import { defineComponent, onMounted, onUnmounted, reactive, ref, toRefs, watch } from 'vue';

  import { Switch, InputSelect, Form } from '@jecloud/ui';

  import VueEvent from '@/helper/model/event';

  import { JE_DATAAUTHORITY_TREECONFIGDATA } from '@/helper/constant';

  export default defineComponent({
    name: 'TreeSelectItem',
    components: {
      JeSwitch: Switch,
      JeInputSelect: InputSelect.Tree,
      JeInputUser: InputSelect.User,
      JeForm: Form,
      JeFormItem: Form.Item,
    },
    props: {
      disable: {
        type: Boolean,
        default: false,
      },
      res: {
        type: String,
        default: '',
      },
      texts: {
        type: String,
        default: '',
      },
      label: {
        type: String,
        default: '',
      },
      info: {
        type: String,
        default: '',
      },
      index: {
        type: String,
        default: '',
      },
      config: {
        type: String,
        default: '',
      },
    },
    emits: ['selectItemChange', 'selectConfigChange'],
    setup(props, { emit }) {
      // 数据
      const formState = reactive({
        texts: '',
        ids: '',
      });
      const controlQuery = ref('0'); // 可见
      const controlEdit = ref('0'); // 可修改
      const controlDelete = ref('0'); // 可删除

      // 设置对象
      const configObj = JE_DATAAUTHORITY_TREECONFIGDATA;

      let _index = ref(null);
      let config = null;
      let res = [];
      onMounted(() => {
        getdata();
      });

      // 初始化数据
      const getdata = () => {
        res = []; // 置空res
        // 父组件传入值赋值
        _index.value = props.index;
        formState.texts = props.texts;
        formState.ids = props.res;
        config = props.config;
        config = config.split(',');
        if (config[0] === '') {
          config.splice(0, 1);
        }
        // config 各项赋值
        config.forEach((item, e) => {
          if (configObj[_index.value][config[e]]) {
            res[e] = configObj[_index.value][config[e]];
          }
        });
        // controlQuery，controlEdit，controlDelete数据赋值
        controlQuery.value = '0';
        controlEdit.value = '0';
        controlDelete.value = '0';
        res.forEach((item) => {
          if (item === 'controlQuery') {
            controlQuery.value = '1';
          } else if (item === 'controlEdit') {
            controlEdit.value = '1';
          } else if (item === 'controlDelete') {
            controlDelete.value = '1';
          }
        });
      };

      const state = reactive({
        controlQuery,
        controlEdit,
        controlDelete,
        _index,
      });

      // 监听state切换
      watch(
        () => state,
        (nv) => {
          Object.keys(nv).forEach((item) => {
            if (nv[item] === '1') {
              if (!res.includes(item)) {
                // 值为1且不存在放入数组
                res.push(item);
              }
            } else {
              // 值不为一，且存在：删除
              if (res.includes(item)) {
                let index = res.indexOf(item);
                res.splice(index, 1);
              }
            }
          });
          // 通知父组件改变数据
          emit('selectConfigChange', _index.value, res);
        },
        { deep: true },
      );

      // 监听树型选择器
      watch(
        () => formState.texts,
        (newvalue, oldvalue) => {
          if (newvalue !== oldvalue) {
            // 通知父组件改变数据
            emit('selectItemChange', _index.value, formState);
          }
        },
      );

      // 数据更新回调
      const setValueCb = () => {
        setTimeout(() => {
          getdata();
        }, 500);
      };

      // 选择事件
      const handleSelect = (row) => {
        const texts = [],
          ids = [];
        if (row?.rows) {
          // 遍历数组在为role情况下数组添加数据
          row.rows.filter((item) => {
            if (item.nodeInfoType === 'role') {
              texts.push(item.text);
              ids.push(item.id);
            }
          });
          // 转化成字符串
          formState.texts = texts.join(',');
          formState.ids = ids.join(',');
        }
      };
      // 删除文件夹
      const selectOptions = {
        title: '角色控制',
        selectExp: "'{nodeInfoType}' != 'folder'",
      };

      VueEvent.on('setValue', setValueCb);
      onUnmounted(() => {
        VueEvent.off('setValue', setValueCb);
      });

      return { formState, ...toRefs(state), selectOptions, handleSelect };
    },
  });
</script>

<style lang="less" scoped>
  .tree-select-item {
    display: inline-block;
    margin-top: 15px;
    padding: 0 15px;
    background: #fff;
    width: 49.5%;
    min-width: 560px;
    height: 155px;
    line-height: 40px;
    .my-textarea {
      height: 100px !important;
    }
    .warp {
      // display: flex;
      // align-items: center;
      // justify-content: space-between;
      .top {
        display: flex !important;
        align-items: center;
        justify-content: space-between;
        width: 100%;
        min-width: 542px;
        height: 40px;
        .left {
          flex: 1;
        }
      }
    }
    :deep(.je-checkbox.je-switch.ant-checkbox-wrapper) {
      margin-left: 0 !important;
    }
  }
</style>
